package yf.mall.controller.api;

import com.github.pagehelper.PageHelper;
import com.yf.annotation.IgnoreAuth;
import com.yf.annotation.LoginUserId;
import com.yf.response.R;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import yf.mall.entity.MallActEntity;
import yf.mall.entity.MallGoodsEntity;
import yf.mall.entity.SaleTypesEntity;
import yf.mall.enums.MallActStatusEnum;
import yf.mall.enums.MallGoodsShelfEnum;
import yf.mall.service.MallActService;
import yf.mall.service.MallGoodsService;
import yf.mall.service.SaleTypesService;

import java.util.*;

/**
 * quequnlong
 */
@RequestMapping("/api/saleTypes")
@RestController
public class ApiSaleTypesController {
    @Autowired
    private SaleTypesService saleTypesService;
    @Autowired
    private MallGoodsService goodsService;
    @Autowired
    private MallActService mallActService;

    @GetMapping("/list")
    @IgnoreAuth
    public R list() {
        List<SaleTypesEntity> saleTypesEntities = saleTypesService.findAllAsc();
        return R.ok(saleTypesEntities);
    }

    /**  quequnlong
     *  根据功能标签id查找商品
     * @param saleType
     * @return
     */
    @GetMapping("/BySaleTypeId")
    public R findGoodsBySaleTypeId(@LoginUserId Long userId, int page, int limit, @RequestParam(required = false) Long type,
                                   Integer saleType,@RequestParam(required = false) String order) {
        if (order == null){
            order = "sort,id Asc";
        }
        //Sort正排序  ID反排序
        PageHelper.startPage(page, limit).setOrderBy(order);
        Map<String,Object> map = new HashMap<>();
        //是首页 不做分类查询 0为首页推荐
        if (type == 0 ){
            type = null;
        }
        map.put("saleType",saleType);
        map.put("shelf", MallGoodsShelfEnum.ON.getIndex());

        List<MallGoodsEntity> mallGoodsEntities = goodsService.findBySaleType(map,type);
        mallGoodsEntities = goodsService.filterByLevel(userId,mallGoodsEntities);
        //获取活动
        for (MallGoodsEntity mallGoodsEntity : mallGoodsEntities) {
            MallActEntity mallActEntity = mallActService.findByGoodsIdAndstatus(mallGoodsEntity.getId(), MallActStatusEnum.OPEN.getIndex());
            if (null!= mallActEntity){
                mallGoodsEntity.setAct(mallActEntity);
            }
        }
        //排序
        sort(mallGoodsEntities);
        return R.ok(mallGoodsEntities);
    }

    //排序
    private void sort(List<MallGoodsEntity> list){
        Collections.sort(list, (o1, o2) ->  {
            if (null != o1.getSort() && null != o2.getSort()){
                if (o1.getSort() > o2.getSort()){
                    return 1;
                }
            }
                return -1;
        });
    }
}
